package com.bwie.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.bwie.common.core.domain.SkuEsModel;
import com.bwie.search.service.ProductService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;

import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public boolean esSaveProduct(List<SkuEsModel> list) {
        BulkRequest bulkRequest = new BulkRequest();
        list.stream().forEach(skuEsModel -> {
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.index("product");
            indexRequest.id(String.valueOf(skuEsModel.getSkuId()));
            indexRequest.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });

        BulkResponse bulk = null;
        try {
            bulk=client.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        boolean b = bulk.hasFailures();
        return b;
    }

    /**
     * 根据spuId删除es中的sku信息
     * @param spuId
     * @return
     */
    @Override
    public void esDelProduct(Long spuId) {
        // 创建DeleteByQueryRequest对象，指定目标索引为"product"
        DeleteByQueryRequest request = new DeleteByQueryRequest("product");

        // 设置查询条件：构建一个term查询，用于精确匹配spuId字段
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("spuId", spuId);
        request.setQuery(termQueryBuilder);

        try {
            // 执行删除操作并获取响应
            BulkByScrollResponse response = client.deleteByQuery(request, RequestOptions.DEFAULT);

            // 处理响应，输出已删除的文档数量
            long deletedDocuments = response.getDeleted();
            System.out.println("已删除文档数: " + deletedDocuments);

        } catch (IOException e) {
            // 捕获并打印可能发生的IO异常
            e.printStackTrace();
        }
    }
}
